package cn.tedu._05weibo.base.exception;

import cn.tedu._05weibo.base.response.JsonResult;
import cn.tedu._05weibo.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){
        String data=ex.getMessage();
        log.error("IllegalArgumentException"+data);
        return JsonResult.fail(data);
    }
    /**
     * 2.第2个异常处理方法: Validation校验DTO类数据的异常;
     *   MethodArgumentNotValidException
     */
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        //获取DTO类属性值校验时的异常提示消息;
        String data = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:" + data);

        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }

    /**
     * 3.第3个异常处理方法:Validation校验声明参数方式接收的数据时的异常;
     *   ConstraintViolationException
     */
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        //获取异常提示消息;
        String data = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:" + data);

        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }
    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException ex){
        String data=ex.getMessage();
        log.error("RuntimeException"+data);
        return JsonResult.fail(data);
    }
    @ExceptionHandler
    public JsonResult doHandleThrowable(Throwable ex){
        String data=ex.getMessage();
        log.error("Throwable"+data);
        return new JsonResult(StatusCode.THROWABLE_ERROR,data);
    }
}





































